<template>
  <div class="container">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
      <el-form :inline="true" :model="filters" :size="size">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="filters.name" placeholder="姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="filters.status" placeholder="请选择" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学期" prop="termId">
          <el-select v-model="filters.termId" placeholder="请选择" clearable>
            <el-option
              v-for="item in termOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="deptName">
          <popup-tree-input
            :data="deptData"
            :props="deptTreeProps"
            :prop="filters.deptName"
            :nodeKey="''+filters.deptId"
            :currentChangeHandle="deptTreeCurrentChangeHandle">
          </popup-tree-input>
        </el-form-item>
        <el-form-item>
          <kt-button :label="$t('action.search')" perms="sys:psyScore:view" type="primary" @click="findPage(null)"/>
        </el-form-item>
        <el-form-item>
          <kt-button :label="$t('action.export')" perms="sys:psyScore:export" type="primary" @click="handleExport" />
        </el-form-item>
        <el-form-item>
          <kt-button :label="$t('action.calculation')" perms="sys:psyScore:calculation" type="primary" @click="handleCalculation" />
        </el-form-item>
      </el-form>
    </div>
    <!--表格内容栏-->
    <kt-table permsView="sys:psyScore:view" permsDelete="sys:psyScore:delete" 
              :data="pageResult" :columns="columns" 
              @findPage="findPage" @handleDelete="handleDelete">
    </kt-table>
  </div>
</template>

<script>
import KtTable from "@/views/Core/KtTable"
import KtButton from "@/views/Core/KtButton"
import PopupTreeInput from "@/components/PopupTreeInput"
import { format } from "@/utils/datetime"

export default {
  components:{
    KtTable,
    KtButton,
    PopupTreeInput
  },
  data() {
    return {
      size: 'small',
      filters: {
        name: '',
        deptId: '',
        deptName: '',
        termId: '',
        status: ''
      },
      columns: [
        {prop:"studentNum", label:"学号", minWidth:100},
        {prop:"username", label:"姓名", minWidth:100},
        {prop:"termName", label:"学期", minWidth:100},
        {prop:"deptName", label:"班级", minWidth:150},
        {prop:"totalScore", label:"总分", minWidth:100},
        {prop:"status", label:"状态", minWidth:100, formatter: this.statusFormat},
        {prop:"createTime", label:"创建时间", minWidth:150, formatter: this.dateFormat}
      ],
      pageRequest: { pageNum: 1, pageSize: 8 },
      pageResult: {},
      
      termOptions: [],
      statusOptions: [
        {id: 0, name: "未完成"},
        {id: 1, name: "已完成"}
      ],
      deptData: [],
      deptTreeProps: {
        label: 'name',
        children: 'children'
      }
    }
  },
  methods: {
    // 获取分页数据
    findPage(data) {
      // 如果传入了pageRequest，更新本地的pageRequest
      if(data && data.pageRequest) {
        this.pageRequest = data.pageRequest;
      }
      
      // 创建查询参数
      let params = {
        pageNum: this.pageRequest.pageNum,
        pageSize: this.pageRequest.pageSize,
        params: []
      };
      
      // 添加过滤条件
      if(this.filters.name) {
        params.params.push({name: 'name', value: this.filters.name});
      }
      
      if(this.filters.deptId) {
        params.params.push({name: 'deptId', value: this.filters.deptId});
      }
      
      if(this.filters.termId) {
        params.params.push({name: 'termId', value: this.filters.termId});
      }
      
      if(this.filters.status || this.filters.status === 0) {
        params.params.push({name: 'status', value: this.filters.status});
      }
      
      console.log('发送查询参数:', params);
      
      this.$api.psyScore.findPage(params).then((res) => {
        this.pageResult = res.data;
        if(data && data.callback) {
          data.callback();
        }
      }).catch(error => {
        console.error('API调用出错:', error);
        this.$message.error('获取数据失败：' + (error.message || '未知错误'));
        if(data && data.callback) {
          data.callback();
        }
      });
    },
    // 批量删除
    handleDelete: function (data) {
      this.$api.psyScore.batchDelete(data.params).then(data!=null?data.callback:'')
    },
    // 时间格式化
    dateFormat: function (row, column, cellValue, index){
      return format(row[column.property])
    },
    // 状态格式化
    statusFormat: function (row, column, cellValue, index){
      if(row.status === 0) {
        return "未完成"
      } else if(row.status === 1) {
        return "已完成"
      }
      return ""
    },
    // 获取学期下拉框选项
    getTermOptions: function (){
      this.$api.busTerm.findOptions(0).then(res => {
        this.termOptions = res.data
        
        // 获取当前学期
        this.$api.busTerm.findCurrentTerm().then(res => {
          if(res.data && res.data.id) {
            this.filters.termId = res.data.id
            this.findPage(null)
          }
        })
      })
    },
    // 获取部门列表
    findDeptTree: function () {
      this.$api.dept.findDeptTree().then((res) => {
        this.deptData = res.data
      })
    },
    // 部门树选中
    deptTreeCurrentChangeHandle (data, node) {
      this.filters.deptId = data.id
      this.filters.deptName = data.name
    },
    // 导出成绩
    handleExport: function() {
      if(this.filters.deptId == '' || this.filters.termId == ''){
        this.$message.error('请选择导出的学期和班级')
      } else {
        this.$api.psyScore.exportScores(this.filters).then(data => {
          let fileName = (new Date()).valueOf() + '-心理测评成绩.xlsx'
          let blob = new Blob([data])
          if ('download' in document.createElement('a')) {
            // 非IE下载
            const elink = document.createElement('a')
            elink.setAttribute('download', decodeURI(fileName))
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放 URL对象
            document.body.removeChild(elink)
          } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
        })
      }
    },
    // 计算排名
    handleCalculation: function() {
      if(this.filters.deptId == '' || this.filters.termId == ''){
        this.$message.error('请选择计算的学期和班级')
      } else {
        this.$api.psyScore.calculateRanking(this.filters).then(res => {
          if(res.code === 200) {
            this.$message.success(res.msg || '计算成功')
            this.findPage(null)
          } else {
            this.$message.error(res.msg || '计算失败')
          }
        })
      }
    }
  },
  mounted() {
    this.getTermOptions()
    this.findDeptTree()
  }
}
</script>

<style scoped>
</style> 